#coding=utf8
#!/usr/bin/python

#from socket import *
import socket
import select
import Queue

host = ''
port = 12345
addr = (host,port)
BUF_SIZE = 1024

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.setblocking(0)

server.bind(addr)
server.listen(10)

rlist = [server]
wlist = []

message_queue = {}

timeout = 1 

while len(rlist):
	print('开始轮询')
	ret_r,ret_w,ret_e = select.select(rlist,wlist,rlist,timeout)
	if not (ret_r or ret_w or ret_e):
		print('select empty')
		continue

	for s in ret_r:
		if s is server:
			cl_sock,cl_addr = server.accept()
			print('connect from %s'%(str(cl_addr)))
			cl_sock.setblocking(0)
			rlist.append(cl_sock)
			message_queue[cl_sock] = Queue.Queue()
		else:
			data = s.recv(BUF_SIZE)
			if data:
				print('recv: %s--from: %s'%(data,s.getpeername()))
				message_queue[s].put(data)
				if s not in wlist:
					wlist.append(s)
			else:
				#可能是客户端主动关闭
				print('disconnet from: %s'%s.getpeername())
				rlist.remove(s)
				if s in wlist:
					wlist.remove(s)
				s.close()
				#从消息队列中删除所有的信息
				del message_queue[s]
	
	for s in ret_w:
		try:
			msg = message_queue[s].get_nowait()
		except Queue.Empty,e:
			print(s.getpeername(),' no data')
			# 如果没有信息要发送，则待发送队列中删除
			wlist.remove(s)
		else:
			s.sendall(msg)
			print('send \' %s \' to %s'%(msg,s.getpeername()))
					
	for s in ret_e:
		print('%s 发生异常'%s.getpeername())
		rlist.remove(s)
		if s in wlist:
			wlist.remove(s)
		s.close()
		del message_queue[s]



